package cn.mumzone.pos.util;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.KeyboardStateObserver;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.ui.adapter.GoodsShopButtonAdapter;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.SalesTimesCard;
import cn.mumzone.pos.model.TimeCardEntity;
import cn.mumzone.pos.ui.adapter.ADA_DialogChooseGoods;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.shopping.AnimShopButton;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;

/**
 * Created by JoeLjt on 2019/7/6.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class GoodsUtil {

    public interface OnSelectedMultipleGoodsListener {
        void OnSelectedMultipleGoods(List<GoodsEntity> selectedList);
    }

    private OnSelectedMultipleGoodsListener l;

    public void setL(OnSelectedMultipleGoodsListener l) {
        this.l = l;
    }

    public static void initScanForGoodsSold(final Context context, final EditText etScan, final EditText etInput,
                                            final TextView.OnEditorActionListener listener, final TextWatcherAdapter watcher) {
        etScan.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return listener == null || listener.onEditorAction(v, actionId, event);
            }
        });

        etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {
                    if (etInput.hasFocus() && !etScan.hasFocus()) {
                        PosToast.INSTANCE.makeShortToast(context, "扫码时软键盘应处于关闭状态，请重试！");
                        v.setText("");
                        EditTextUtil.hideSoftInput(context, etInput);
                        return true;
                    }
                }
                return true;
            }
        });

        KeyboardStateObserver.getKeyboardStateObserver((Activity) context)
                .setKeyboardVisibilityListener(new KeyboardStateObserver.OnKeyboardVisibilityListener() {
                    @Override
                    public void onKeyboardShow() {
                        Elog.e("SCAN------> ", "onKeyboardShow");
                        etScan.setText("");
                        etScan.clearFocus();
                    }

                    @Override
                    public void onKeyboardHide() {
                        Elog.e("SCAN------> ", "onKeyboardHide");
                        etScan.requestFocus();
                        etInput.clearFocus();
                    }
                });


        etInput.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (watcher != null) {
                    watcher.onTextChanged(charSequence, i, i1, i2);
                }
            }
        });

        etInput.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
        });


    }

    public static void showGoodsSelectDialog(final Context context, boolean isBindMember, List<GoodsEntity> localList,
                                             final List<GoodsEntity> goodsEntities, final OnSelectedMultipleGoodsListener listener) {

        for (GoodsEntity goodsEntity : goodsEntities) {
            if (!ListUtil.isListEmpty(localList)) {
                for (GoodsEntity localCartBean : localList) {
                    if (goodsEntity.getGoodsId().equals(localCartBean.getGoodsId()) && "1".equals(goodsEntity.getGoodsBatchNum())) {
                        int maxQuantity = Integer.parseInt(BigDecimalUtil.getNumber(goodsEntity.getGoodsQuantity()))
                                - Integer.parseInt(BigDecimalUtil.getNumber(localCartBean.getGoodsCount()));
                        goodsEntity.setGoodsQuantity(String.valueOf(maxQuantity));
                    }
                }
            }
        }

        final AlertDialog chooseGoodsDialog = new PosDialog.PosBuilder(context, PosDialog.CONFIRM_TYPE_WITH_TEXT_SHADOW)
                .setRealDialogContent(R.layout.dialog_choose_goods_new)
                .setDialogTitle("一码多物")
                .setSingleConfirmText("确定")
                .setBottomText("总共选择 0 件商品", null)
                .setWidthAndHeight(360, 420)
                .show();

        final LRecyclerView chooseGoodsRv = chooseGoodsDialog.getView(R.id.root_dialog_choose_goods);
        chooseGoodsRv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        final ADA_DialogChooseGoods adapter = new ADA_DialogChooseGoods(context, isBindMember);
        chooseGoodsRv.setAdapter(new LRecyclerViewAdapter(adapter));
        chooseGoodsRv.setPullRefreshEnabled(false);
        chooseGoodsRv.setLoadMoreEnabled(false);
        chooseGoodsRv.setHasFixedSize(false);
        adapter.update(goodsEntities, true);

        adapter.setOnGoodsAmountChangedListener(new ADA_DialogChooseGoods.OnGoodsAmountChangedListener() {
            @Override
            public void onAmountChanged() {
                TextView goodsCount = chooseGoodsDialog.getView(R.id.tv_bottom_text);
                StringSpanUtils str = StringSpanUtils.init().addStr("总共选择 " + adapter.getSelectedCount() + " 件商品");
                str.setForeColorWithKeyAndPosition(StringUtils.get(adapter.getSelectedCount()),
                        0, context.getResources().getColor(R.color.black_color));
                goodsCount.setText(str.build());
            }
        });

        final LoadingButton lbConfirm = chooseGoodsDialog.getView(R.id.lb_confirm);
        lbConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<GoodsEntity> selectedList = adapter.getSelectedList();
                if (ListUtil.isListEmpty(selectedList)) {
                    ToastUtil.makeText(context, "请选择商品", false);
                    return;
                }
                lbConfirm.startLoading("请稍候");


                // 把选择的商品添加到 cartList，然后同步购物车信息
                if (listener != null) {
                    listener.OnSelectedMultipleGoods(selectedList);
                    lbConfirm.startLoading("确定");
                }

                chooseGoodsDialog.dismiss();
            }
        });

    }

    public static AlertDialog showEditGoodsDialog(final Context context, final GoodsEntity entity, final View.OnClickListener listener) {

        sModifyingGoods = JSON.toJSONString(entity);

        final AlertDialog editGoodsDialog = new PosDialog.PosBuilder(context, PosDialog.CONFIRM_TYPE_NORMAL)
                .setRealDialogContent(R.layout.dialog_modify_goods_info)
                .setDialogTitle("修改商品信息")
                .setSingleConfirmText("确定")
                .setWidth(359)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {

                        if (!isModifiedGoods(entity)) {
                            dialog.dismiss();
                            return;
                        }

                        if (listener != null) {
                            LoadingButton lbConfirm = dialog.getView(R.id.lb_confirm);
                            lbConfirm.startLoading("正在修改");
                            listener.onClick(lbConfirm);
                        }
                    }
                })
                .show();

        // 商品名称
        TextView goodsTitle = editGoodsDialog.getView(R.id.tv_goods_title);
        goodsTitle.setText(entity.getGoodsName());

        // 议价
        LinearLayout llBargainTop = editGoodsDialog.getView(R.id.ll_bargain_layout);
        final LinearLayout llBargainRealContent = editGoodsDialog.getView(R.id.ll_bargain_content);
        final CheckBox cbBargain = editGoodsDialog.getView(R.id.rb_check_bargain);
        llBargainTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbBargain.setChecked(!cbBargain.isChecked());
            }
        });

        // 议价-原价
        final TextView tvOrigin = editGoodsDialog.getView(R.id.tv_origin_price);
        tvOrigin.setText(entity.getPrice());

        // 议价-议价
        final TextView tvBargain = editGoodsDialog.getView(R.id.tv_bargain_price);
        tvBargain.setText(entity.getBargainPrice());
        if (StringUtils.isNumber(entity.getBargainPrice()) && Double.parseDouble(entity.getBargainPrice()) > 0) {
            cbBargain.setChecked(true);
            llBargainRealContent.setVisibility(View.VISIBLE);
        }

        // 议价-呼出键盘
        final LinearLayout llBargainPrice = editGoodsDialog.getView(R.id.ll_bargain_price);
        llBargainPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showModifyBargainDialog(context, (TextView) editGoodsDialog.getView(R.id.tv_bargain_price), entity);
            }
        });

        cbBargain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                tvBargain.setText(entity.getBargainPrice());
                llBargainRealContent.setVisibility(isChecked ? View.VISIBLE : View.GONE);

                TextView tvBargainHintOne = editGoodsDialog.getView(R.id.tv_bargain_hint_one);
                tvBargainHintOne.setVisibility(isChecked ? View.GONE : View.VISIBLE);

                if (!isChecked) {
                    entity.setBargainPrice("0");
                }
            }
        });

        // 寄存
        View vSave = editGoodsDialog.getView(R.id.ll_save_layout);
        final TextView tvSaveHint = editGoodsDialog.getView(R.id.tv_save_Hint);
        final AnimShopButton vSaveAmount = editGoodsDialog.getView(R.id.tv_save_amount);
        vSaveAmount.setOnAddDelListener(new GoodsShopButtonAdapter(context) {
            @Override
            protected void onAmountChanged(int count) {
                entity.setRegisterCount(StringUtils.get(count));
            }

            @Override
            public void onAddFailed(int count, FailType failType) {
                ToastUtil.makeText(context, "寄存数量不能大于购买数量~", false);
            }

        });

        final CheckBox cbSave = editGoodsDialog.getView(R.id.rb_check_save);
        vSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbSave.setChecked(!cbSave.isChecked());
            }
        });

        if (Integer.parseInt(entity.getRegisterCount()) > 0) {
            tvSaveHint.setVisibility(View.GONE);
            vSaveAmount.setVisibility(View.VISIBLE);
            cbSave.setChecked(true);
            vSaveAmount.setCount(Integer.parseInt(entity.getRegisterCount()));
            vSaveAmount.setMaxCount(Integer.parseInt(entity.getGoodsCount()));
        }

        cbSave.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                tvSaveHint.setVisibility(isChecked ? View.GONE : View.VISIBLE);

                vSaveAmount.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                vSaveAmount.setCount(Math.max(Integer.parseInt(entity.getRegisterCount()), 1));
                entity.setRegisterCount(StringUtils.get(Math.max(Integer.parseInt(entity.getRegisterCount()), 1)));
                vSaveAmount.setMaxCount(Integer.parseInt(entity.getGoodsCount()));

                if (!isChecked) {
                    entity.setRegisterCount("0");
                }

            }
        });

        // 赠送
        View vPresent = editGoodsDialog.getView(R.id.ll_present_layout);
        final TextView tvPresentHint = editGoodsDialog.getView(R.id.tv_present_hint);
        final AnimShopButton vPresentAmount = editGoodsDialog.getView(R.id.tv_present_amount);
        vPresentAmount.setOnAddDelListener(new GoodsShopButtonAdapter(context) {
            @Override
            protected void onAmountChanged(int count) {
                entity.setPresentNum(count);
            }

            @Override
            public void onAddFailed(int count, FailType failType) {
                ToastUtil.makeText(context, tvPresentHint.getText().toString(), false);
            }
        });

        final CheckBox cbPresent = editGoodsDialog.getView(R.id.rb_check_present);
        vPresent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbPresent.setChecked(!cbPresent.isChecked());
            }
        });

        // 赠送-反选
        if (entity.getPresentNum() > 0) {
            tvPresentHint.setVisibility(View.GONE);
            vPresentAmount.setVisibility(View.VISIBLE);
            cbPresent.setChecked(true);
            vPresentAmount.setCount(entity.getPresentNum());
            vPresentAmount.setMaxCount(Integer.parseInt(entity.getGoodsCount()));
        }

        cbPresent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                tvPresentHint.setVisibility(isChecked ? View.GONE : View.VISIBLE);

                vPresentAmount.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                vPresentAmount.setCount(Math.max(entity.getPresentNum(), 1));
                entity.setPresentNum(Math.max(entity.getPresentNum(), 1));
                vPresentAmount.setMaxCount(Integer.parseInt(entity.getGoodsCount()));

                if (!isChecked) {
                    entity.setPresentNum(0);
                }

            }
        });

        // 数量加减
        AnimShopButton vAmount = editGoodsDialog.getView(R.id.v_goods_amount);
        vAmount.setCount(Integer.parseInt(entity.getGoodsCount()));
        vAmount.setMinCount(1);
        if ("1".equals(entity.getGoodsBatchNum())) {
            vAmount.setMaxCount(Integer.parseInt(entity.getGoodsQuantity()));
        }
        vAmount.setOnAddDelListener(new GoodsShopButtonAdapter(context) {

            @Override
            protected void onAmountChanged(int count) {

                entity.setGoodsCount(StringUtils.get(count));
                entity.setSelectCount(count);

                AnimShopButton vSaveAmount = editGoodsDialog.getView(R.id.tv_save_amount);
                vSaveAmount.setMaxCount(count);
                if (cbSave.isChecked()) {
                    if (vSaveAmount.getCount() > count) {
                        vSaveAmount.setCount(count);
                    }
                    vSaveAmount.invalidate();
                }

                AnimShopButton vPresentAmount = editGoodsDialog.getView(R.id.tv_present_amount);
                vPresentAmount.setMaxCount(count);
                if (cbPresent.isChecked()) {
                    if (vPresentAmount.getCount() > count) {
                        vPresentAmount.setCount(count);
                    }
                    vPresentAmount.invalidate();
                }

            }

        });

        return editGoodsDialog;
    }

    public static AlertDialog showModifyBargainDialog(final Context context, final TextView tvTarget, final GoodsEntity entity) {

        final AlertDialog bargainDialog = new PosDialog.PosBuilder(context)
                .setRealDialogContent(R.layout.dialog_modify_bargain_price)
                .setDialogNoConfirm()
                .setDialogTitle("修改议价金额")
                .setWidth(438)
                .show();

        TextView originPrice = bargainDialog.getView(R.id.tv_origin_price);
        originPrice.setText(entity.getPrice());

        final EditText etModify = bargainDialog.getView(R.id.et_modify);
        etModify.setHint(entity.getBargainPrice());
        MoneyFormatUtil.formatMoney(etModify, null);
        PosKeyBoardView keyBoardView = bargainDialog.getView(R.id.keyboard_view);
        keyBoardView.attachTo(etModify);
        keyBoardView.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                String bargainPrice = MoneyFormatUtil.getFormattedMoney(text, false);
                if (TextUtils.isEmpty(bargainPrice)) {
                    ToastUtil.makeText(context, "议价金额不可以为零！", false);
                    return;
                }
                LedDisplayUtil ledDisplayUtil = new LedDisplayUtil(context);
                ledDisplayUtil.displayPrice(bargainPrice);
                if (tvTarget != null) tvTarget.setText(bargainPrice);
                entity.setBargainPrice(bargainPrice);
                bargainDialog.dismiss();
            }
        });

        return bargainDialog;
    }


    public static void showCheckGoodsInventoryResultDialog(Context context,String tips, String goodsName) {
        AlertDialog tipDialog = new PosDialog.PosBuilder(context, PosDialog.DIALOG_NO_TITLE)
                .setRealDialogContent(R.layout.dialog_check_goods_result)
                .setSingleConfirmText("确定")
                .setWidth(359)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        dialog.dismiss();
                    }
                })
                .show();
        tipDialog.setText(R.id.tv_goods_list, goodsName);
        tipDialog.setText(R.id.tv_tip, tips);
    }


    public static void showModifyCountDialog(final Context context, final PosKeyBoardView.OnConfirmClickListener onConfirmClickListener) {

        final AlertDialog bargainDialog = new PosDialog.PosBuilder(context)
                .setRealDialogContent(R.layout.dialog_modify_count)
                .setDialogNoConfirm()
                .setDialogTitle("修改数量")
                .setWidth(438)
                .show();
        bargainDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        final EditText etCount = bargainDialog.getView(R.id.et_count);
        MoneyFormatUtil.formatMoney(etCount, null);
//        etCount.setText(count);
        etCount.requestFocus();
        EditTextUtil.hideSoftInputMethod(context, etCount);
        PosKeyBoardView keyBoardView = bargainDialog.getView(R.id.keyboard_view);
        keyBoardView.attachTo(etCount);
        keyBoardView.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                onConfirmClickListener.onConfirmClick(text);
                bargainDialog.dismiss();
            }
        });
        bargainDialog.show();
    }

    /**
     * 更新本地购物车列表
     */
    public static void updateLocalCartList(LinkedList<GoodsEntity> localList, List<GoodsEntity> newList) {

        outerLoop:
        for (int i = 0; i < newList.size(); i++) {
            GoodsEntity recentAddGoodsBean = newList.get(i).clone();
            for (int j = 0; j < localList.size(); j++) {
                GoodsEntity localCartBean = localList.get(j);

                // 获取到购物车列表后，与内存中列表数据进行 id 匹配
                String recentAddGoodsSpecJson = JSON.toJSONString(recentAddGoodsBean.getGoodsSpec());
                String localGoodsSpecJson = JSON.toJSONString(localCartBean.getGoodsSpec());

                if (recentAddGoodsBean.getGoodsId().equals(localCartBean.getGoodsId())
                        && recentAddGoodsSpecJson.hashCode() == localGoodsSpecJson.hashCode()) {

                    // 如果是同一个商品，更新商品数量和寄存数量
                    localCartBean.setGoodsCount(getCount(localCartBean.getGoodsCount(), recentAddGoodsBean.getGoodsCount()));
                    localCartBean.setRegisterCount(getCount(localCartBean.getRegisterCount(), recentAddGoodsBean.getRegisterCount()));
                    localCartBean.setSelectCount(Integer.parseInt(localCartBean.getGoodsCount()));

                    continue outerLoop;
                }

            }

            // 为新插入的数据设置选中数量
            // 默认为 0，设为 1；一码多物时手动指定数量，不做处理
            int selectCount = recentAddGoodsBean.getSelectCount();
            if (selectCount == 0) {
                selectCount += 1;
            }
            recentAddGoodsBean.setSelectCount(selectCount);

            // 如果有新数据，则插入链表最后
            localList.addFirst(recentAddGoodsBean);
        }
    }

    private static String getCount(String origin, String newAdd) {
        int originNum = Integer.parseInt(origin);
        int newAddNum = Integer.parseInt(newAdd);
        return StringUtils.get(originNum + newAddNum);
    }

    /**
     * 添加商品到购物车前的准备工作
     *
     * @param context
     * @param localList
     * @param entity
     * @param list
     * @return
     */
    public static List<GoodsEntity> prepareToAddGoodsToCart(Context context, LinkedList<GoodsEntity> localList,
                                                            GoodsEntity entity, List<GoodsEntity> list) {

        if (entity != null && list != null) {
            throw new RuntimeException("Either entity or list must be null!");
        }

        ArrayList<GoodsEntity> postList = new ArrayList<>();
        if (entity != null) {
            postList.add(entity);
        } else {
            postList.addAll(list);
        }

        // 配置默认参数
        for (GoodsEntity goodsEntity : postList) {
            goodsEntity.setGoodsCount(StringUtils.isNumber(goodsEntity.getGoodsCount()) ? goodsEntity.getGoodsCount() : "1");
            goodsEntity.setBargainPrice("0");
            goodsEntity.setRegisterCount("0");
            goodsEntity.setStoreId(AppConstants.TEMP_SHOP_ID);
            goodsEntity.setSellerId(AppConstants.TEMP_SELLER_ID);

            if (!isGoodsAvailable(localList, goodsEntity)) {
                ToastUtil.makeText(context, "商品库存不足！", false);
                return null;
            }
        }

        return postList;
    }

    /**
     * 处理带批次的商品
     * <p>
     * 当前要添加的商品数量 + 购物车中现有的该商品数量 <= 库存数量
     *
     * @param goodsEntity
     */
    public static boolean isGoodsAvailable(LinkedList<GoodsEntity> localList, GoodsEntity goodsEntity) {

        if ("1".equals(goodsEntity.getGoodsBatchNum())) {
            int goodQuantity = Integer.parseInt(StringUtils.isNumber(goodsEntity.getGoodsQuantity()) ? goodsEntity.getGoodsQuantity() : "0");
            int goodsCount = Integer.parseInt(goodsEntity.getGoodsCount());
            int goodsCountInCart = 0;

            for (GoodsEntity cartEntity : localList) {
                if (goodsEntity.getGoodsSkuId().equals(cartEntity.getGoodsSkuId())) {
                    goodsCountInCart = Integer.parseInt(cartEntity.getGoodsCount());
                }
            }
            return (goodsCount + goodsCountInCart) <= goodQuantity;
        }
        return true;

    }

    public static void updateSelectCountAndAmountForGoods(TextView tvTotalCount, TextView tvTotalPrice, List<GoodsEntity> goodsList, boolean isBindMember) {

        int totalCount = 0;
        if (!ListUtil.isListEmpty(goodsList)) {
            for (GoodsEntity goodsEntity : goodsList) {
                totalCount += goodsEntity.getSelectCount();
            }
        }
        tvTotalCount.setText(StringUtils.getString(totalCount));

        double amount = 0.0d;
        if (!ListUtil.isListEmpty(goodsList)) {
            for (GoodsEntity entity : goodsList) {
                String goodsPrice = entity.getPrice();
                if (Double.parseDouble(entity.getBargainPrice()) > 0) {
                    goodsPrice = entity.getBargainPrice();
                } else if (Double.parseDouble(BigDecimalUtil.getNumber(entity.getSecondPrice())) > 0) {
                    goodsPrice = entity.getSecondPrice();
                } else if (isBindMember) {
                    goodsPrice = StringUtils.get(entity.getMemberPrice(), entity.getPrice());
                }

                String goodsCount = StringUtils.get(Integer.parseInt(entity.getGoodsCount()) - entity.getPresentNum());
                amount = BigDecimalUtil.add(String.valueOf(amount),
                        String.valueOf(BigDecimalUtil.mul(goodsCount, goodsPrice)));
            }
        }
        tvTotalPrice.setText(StringUtils.getFormattedMoneyWithUnit(String.valueOf(amount)));

    }

    public static void updateGoodsSelectStatus(RecyclerView.Adapter adapter, List<GoodsEntity> adapterList, List<GoodsEntity> localList) {
        for (GoodsEntity entity : adapterList) {
            entity.setSelectCount(0);
            for (GoodsEntity cartEntity : localList) {
                if (cartEntity.getGoodsSkuId().equals(entity.getGoodsSkuId())) {
                    entity.setSelectCount(cartEntity.getSelectCount());
                    break;
                }
            }
        }
        adapter.notifyDataSetChanged();
    }


    public static void syncLocalAndRemotePrice(List<GoodsEntity> remoteList, List<GoodsEntity> localList) {
        if (ListUtil.isListEmpty(localList) || ListUtil.isListEmpty(remoteList)) {
            return;
        }
        for (GoodsEntity localEntity : localList) {
            for (GoodsEntity remoteEntity : remoteList) {
                if (remoteEntity.getGoodsSkuId().equals(localEntity.getGoodsSkuId())) {
                    if (!StringUtils.isEmpty(localEntity.getPrice()) && !StringUtils.isEmpty(remoteEntity.getPrice())
                            && !localEntity.getPrice().equals(remoteEntity.getPrice())) {
                        localEntity.setPrice(remoteEntity.getPrice());
                    }
                    if (!StringUtils.isEmpty(localEntity.getMemberPrice()) && !StringUtils.isEmpty(remoteEntity.getMemberPrice())
                            && !localEntity.getMemberPrice().equals(remoteEntity.getMemberPrice())) {
                        localEntity.setMemberPrice(remoteEntity.getMemberPrice());
                    } else if (StringUtils.isEmpty(localEntity.getMemberPrice()) && !StringUtils.isEmpty(remoteEntity.getMemberPrice())) {
                        localEntity.setMemberPrice(remoteEntity.getMemberPrice());
                    } else if (!StringUtils.isEmpty(localEntity.getMemberPrice()) && StringUtils.isEmpty(remoteEntity.getMemberPrice())) {
                        localEntity.setMemberPrice(remoteEntity.getMemberPrice());
                    }

                    if (!StringUtils.isEmpty(localEntity.getSecondPrice()) && !StringUtils.isEmpty(remoteEntity.getSecondPrice())
                            && !localEntity.getSecondPrice().equals(remoteEntity.getSecondPrice())) {
                        localEntity.setSecondPrice(remoteEntity.getSecondPrice());
                    }
                }
            }
        }
    }

    public static String getGoodsPriceByMember(MemberEntity memberEntity, GoodsEntity entity) {
        String goodsPrice;
        if (Double.parseDouble(BigDecimalUtil.getNumber(entity.getBargainPrice())) > 0) {
            goodsPrice = entity.getBargainPrice();
        } else {
            if (memberEntity != null && MemberEntity.DISCOUNT_TYPE_DISCOUNT.equals(memberEntity.getDiscountType())) {

                // 如果有会员价，展示会员价
                if (Double.parseDouble(BigDecimalUtil.getNumber(entity.getMemberPrice())) != 0) {
                    goodsPrice = entity.getMemberPrice();
                } else {
                    if (StringUtils.isNumber(entity.getSecondPrice()) && Double.parseDouble(entity.getSecondPrice()) != 0) {
                        // 如果有变价，展示变价
                        goodsPrice = entity.getSecondPrice();
                    } else {
                        goodsPrice = entity.getPrice();
                    }
                }

            } else {
                if (StringUtils.isNumber(entity.getSecondPrice()) && Double.parseDouble(entity.getSecondPrice()) != 0) {
                    // 如果有变价，展示变价
                    goodsPrice = entity.getSecondPrice();
                } else {
                    // 如果有会员价，展示会员价
                    if (memberEntity != null && Double.parseDouble(BigDecimalUtil.getNumber(entity.getMemberPrice())) != 0) {
                        goodsPrice = entity.getMemberPrice();
                    } else {
                        goodsPrice = entity.getPrice();
                    }
                }
            }
        }
        return goodsPrice;
    }

    // 检查是否对传入的 GoodsEntity 进行过操作
    private static String sModifyingGoods = "";

    private static boolean isModifiedGoods(GoodsEntity entity) {
        return !sModifyingGoods.equals(JSON.toJSONString(entity));
    }

    public static boolean isLimitTimeCard(SalesTimesCard salesTimesCard) {
        return (!StringUtils.isEmpty(salesTimesCard.getUseExcludeDate()) && !"".equals(salesTimesCard.getUseExcludeDate())) || !ListUtil.isListEmpty(salesTimesCard.getTimeList());
    }

    public static boolean isLimitTimeCard(TimeCardEntity timeCardEntity) {
        return (!StringUtils.isEmpty(timeCardEntity.getAvailableWeek()) && !"".equals(timeCardEntity.getAvailableWeek())) || !ListUtil.isListEmpty(timeCardEntity.getAvailableTimes());
    }


    public static String getFormatLimitInfo(TimeCardEntity timeCardEntity) {
        StringBuilder builder = new StringBuilder();
        if (!StringUtils.isEmpty(timeCardEntity.getAvailableWeek()) && !"".equals(timeCardEntity.getAvailableWeek())) {
            builder.append(timeCardEntity.getAvailableWeek());
        }
        if (!ListUtil.isListEmpty(timeCardEntity.getAvailableTimes())) {
            for (int index = 0; index < timeCardEntity.getAvailableTimes().size(); index++) {
                SalesTimesCard.TimeListBean bean = timeCardEntity.getAvailableTimes().get(index);
                builder.append(String.format("%s-%s", AppDateUtil.getDateToString(bean.getStartTime(), AppDateUtil.HH_MM),
                        AppDateUtil.getDateToString(bean.getEndTime(), AppDateUtil.HH_MM)));
                if (index < timeCardEntity.getAvailableTimes().size() - 1) {
                    builder.append("、");
                }
            }
        }
        return builder.toString();
    }
}
